﻿namespace System.Data.Entity.Utilities
{
    using System.Data.Entity.Core.Objects;
    using System.Data.Entity.Infrastructure;
    using System.Globalization;
    using System.Linq;

    public static class DbContextExtensions
    {
        /// <summary>
        /// Is a function used to perform a SQL Server full-text search on full-text indexed columns
        /// containing character-based data types. 
        /// This function returns a table of zero, one, or more rows for those columns 
        /// containing values that match the meaning and not just the exact wording, 
        /// of the text in the specified <paramref name="freetext"/>.
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="context"></param>
        /// <param name="freetext">Is text to search for in the column_name.
        /// Any text, including words, phrases or sentences, can be entered.
        /// Matches are generated if any term or the forms of any term is found in the full-text index.
        /// <paramref name="freetext"/> is wordbroken, stemmed, and passed through the thesaurus.</param>
        /// <returns></returns>
        public static IQueryable<TEntity> DbSearch<TEntity>(this DbContext context, string freetext)
            where TEntity : class
        {
            var _freetext = string.Format(CultureInfo.InvariantCulture, "{0}(@{1})",

                //Utilities.FunctionQualifiedNamePattern(context.GetType().Name, typeof(TEntity).Name),

                context.GetType().Name + "." + Utilities.DefaultFunctionPrefix + typeof(TEntity).Name,
                Utilities.DefaultParameterName);

            return ((IObjectContextAdapter)context).ObjectContext
                .CreateQuery<TEntity>(
                    _freetext,
                    new ObjectParameter(Utilities.DefaultParameterName, freetext)
                    );
        }
    }
}
